#include "p24fj256gb110.h"
#include "stdio.h"

#include "GOTHglobal.h"
#include "GOTHgpio.h"
#include "GOTHuart.h"
#include "GOTHtraps.h"
#include "GOTHad.h"

#ifdef _RELEASE_
// config word for release
_CONFIG1( JTAGEN_OFF & GCP_OFF & GWRP_OFF & BKBUG_OFF & COE_OFF & FWDTEN_OFF & ICS_PGx1) 
_CONFIG2( IESO_OFF & FCKSM_CSDCMD & OSCIOFNC_OFF & POSCMOD_HS & FNOSC_PRI & PLLDIV_DIV2 & IOL1WAY_ON)
_CONFIG3( WPCFG_WPCFGDIS & WPDIS_WPDIS)		//Disable erase/write protect of all memory regions.

#endif
#ifdef _DEBUG_
// config word for debug
_CONFIG1( JTAGEN_OFF & GCP_OFF & GWRP_OFF & BKBUG_ON & COE_OFF & FWDTEN_OFF & ICS_PGx1) 
_CONFIG2( IESO_OFF & FCKSM_CSDCMD & OSCIOFNC_OFF & POSCMOD_HS & FNOSC_PRI & PLLDIV_DIV2 & IOL1WAY_ON)
_CONFIG3( WPCFG_WPCFGDIS & WPDIS_WPDIS)		//Disable erase/write protect of all memory regions.
#endif

int main(void){
	GPIO_InitLeds();
	GPIO_SetLeds(0x55);
	GPIO_InitBtns(BOTH_BTNS);
	GPIO_EnableBtns(BOTH_BTNS);
	GPIO_InitDips();
	UART_InitUart();
	AD_InitAdc();
	AD_InitComparator();
	
	unsigned char uart_in[10];
	while(1){
		// leds and butttons example
		if(GPIO_Btn1Pressed() != 0){
			GPIO_ToggleLeds(RED_LED_0 | ORANGE_LED_2 | ORANGE_LED_1 | ORANGE_LED_0);
		}
		else{
			if(GPIO_Btn2Pressed() != 0){
				double voltage;
				char result[7];
				AD_AdcMeasure();
				voltage = (3.3 * AD_AdcGetValue(GPIO_GetDipsValue()))/1024;
				sprintf(result,"V: %3.1f\n",voltage);
				UART_WriteBuffer((unsigned char *)result,7);
				voltage = (3.3 * AD_AdcGetValue(ADC_CHANNEL_4))/1024;
				sprintf(result,"V: %3.1f\n",voltage);
				UART_WriteBuffer((unsigned char *)result,7);
			}
		}
		// uart and leds example
		if(UART_ReadBuffer(uart_in,1) == 1){
			switch (uart_in[0]){
				case 'a':{
					GPIO_SetLeds(ALL_LEDS);
					UART_WriteBuffer((unsigned char *)"Leds on.\n",9);
				} break;
				case 'o':{
					GPIO_ClearLeds(ALL_LEDS);
					UART_WriteBuffer((unsigned char *)"Leds off.\n",10);
				} break;
				case 't':{ 
					GPIO_ToggleLeds(ALL_LEDS);
					UART_WriteBuffer((unsigned char *)"Leds toggled.\n",14);
				} break;
				case 'e':{ 
					UART_WriteBuffer((unsigned char *)"Divide by 0.\n",13);
					unsigned int i;
					int x, j = 10;
					for(i=65535; i>= 0; i--){
						x = j/i;
					}
				} break;
				case 'c':{ 
					UART_WriteBuffer((unsigned char *)"Compare:\n",9);
					if(AD_CompareA2C() == 0){
						UART_WriteBuffer((unsigned char *)"\tA < C.\n",8);
					}
					else{
						UART_WriteBuffer((unsigned char *)"\tA > C.\n",8);
					}
					if(AD_CompareA2D() == 0){
						UART_WriteBuffer((unsigned char *)"\tA < D.\n",8);
					}
					else{
						UART_WriteBuffer((unsigned char *)"\tA > D.\n",8);
					}
				} break;
				default:{
					UART_WriteBuffer((unsigned char *)"Unkown command.\n",16);
				} break;
			}
		}
    }
}
//*****************************************************************************
